package net.xiaosaguo.mymall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xiaosaguo.common.utils.PageUtils;
import net.xiaosaguo.common.utils.Query;
import net.xiaosaguo.mymall.product.dao.ProductAttrValueDao;
import net.xiaosaguo.mymall.product.entity.ProductAttrValueEntity;
import net.xiaosaguo.mymall.product.service.ProductAttrValueService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveProductAttr(List<ProductAttrValueEntity> productAttrValueEntityList) {
        this.saveBatch(productAttrValueEntityList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> list) {
        // 1. 将以前所有的旧属性直接删除
        this.lambdaUpdate().eq(ProductAttrValueEntity::getSpuId, spuId).remove();
        // 2. 将新属性插入
        List<ProductAttrValueEntity> collect = list
                .stream()
                .peek(item -> item.setSpuId(spuId))
                .collect(Collectors.toList());
        this.saveBatch(collect);
    }

}